package com.huangpeng.designmodel.highConcurrency;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * @Author huangpeng
 * @Title Callable接口
 * @Package
 * @Date 2021/1/25 14:47
 * @Description 之前多线程实现 Runnable 接口是执行工作独立任务，没有返回值，而Callable接口可以在任务完成之后将期望值返回，实现Callable接口，重写call()方法。
 * @Version 1.0
 *
 * Callable线程是异步重启线程，如果要开启多个Callable线程，需要创建多个FutureTask
 */
class MyThread implements Callable<Integer>{

    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName() + "**************** come Callable ");
        TimeUnit.SECONDS.sleep(3);
        return 1024;
    }
}
public class CallableDemo {
    public static void main(String[] args) throws Exception {
        FutureTask<Integer> futureTask1 = new FutureTask<>(new MyThread());
        FutureTask<Integer> futureTask2 = new FutureTask<>(new MyThread());
        new Thread(futureTask1,"AA").start();
        new Thread(futureTask2,"BB").start();
        System.out.println(Thread.currentThread().getName() + "**************** come main ");
        int result = 100;
        //futureTask.isDone()表示该线程是否执行完毕
        while (!futureTask1.isDone() || !futureTask2.isDone()){

        }
        //futureTask.get() 获得Callable线程的计算结果，
        // 如果没有计算完成就要强行获取Callable值，会导致堵塞，直到计算完成
        System.out.println("************************ result1: " + (result+futureTask1.get()));
        System.out.println("************************ result2: " + (result+futureTask2.get()));
    }
}
